<?php
function login_check(){
		global $db,$web_dbtop,$web_dir;
		$loginjl=0;
		if (empty($_COOKIE["usersid"]) || empty($_COOKIE["password"]) || empty($_COOKIE["username"])){
		   		echo "<script>location.href='/login.php';</script>";
	  		exit;
		}else{
			if(!isset($_SESSION['usersid']))
			{
				$ip = usersip();
				$username = str_check($_COOKIE["username"]);
				$pwd = str_check($_COOKIE["password"]);
	            $sql = "call web_user_login('{$username}','{$pwd}','{$ip}')";
	            $arr = $db->Mysqli_Multi_Query($sql);
	            switch($arr[0][0]["result"])
	            {
	                case 0: //成功
	                    $_SESSION["usersid"] = $arr[0][0]["userid"];
	                    $_SESSION["username"] = $arr[0][0]["username"];
	                    $_SESSION["password"] = $pwd;
	                    $_SESSION["nickname"] = $arr[0][0]["nickname"];
	                    $_SESSION["points"] = $arr[0][0]["points"];
	                    $_SESSION["bankpoints"] = $arr[0][0]["bankpoint"];
	                    $_SESSION["exp"] = $arr[0][0]["experience"];
	                    $_SESSION['freeze'] = 0;
	                    setcookie("usersid",$arr[0][0]["userid"]);
	                    setcookie("username",$arr[0][0]["username"]);
	                    setcookie("password",$pwd);
	                case 2: //帐号被冻结
                		setcookie("usersid");
	                    setcookie("username");
	                    setcookie("password");
	                    echo "<script language=javascript>alert('很抱歉!您帐号被冻结无法登录，请与客服联系!');location.href='/';</script>";
	                    exit;
	                case 99: //数据库错误
	                    echo "<script language=javascript>alert('很抱歉!由于系统故障暂时无法登录，请与客服联系!');location.href='/';</script>";
	                    exit;
	                default:
	                    echo "<script language=javascript>location.href='/login.php';</script>";
	                    exit;
	            }
			}
			//如果帐号被冻结，立即注销退出
			if(isset($_SESSION['freeze']) && $_SESSION['freeze'] == 1)
			{
				//退出
				session_destroy();
	            setcookie("usersid");
	            setcookie("username");
	            setcookie("password");
	            echo "<script language=javascript>location.href='index.php';</script>";
	            exit;
			}
	   }
}
/* 取得用户组名
*
*/
function GetUserGroupName()
{
	global $db;
	$ret = "";
	$sql = "select experience from users where id = '{$_SESSION['usersid']}'";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$exp = $rs['experience'];
		$sql = "select name from usergroups where {$exp} BETWEEN creditslower AND creditshigher ";
		$r = $db->query($sql);
		if($rg = $db->fetch_array($r))
		{
			$ret = $rg["name"];
		}
	}
	return $ret;
}
/* 更新分数
 *
*/
function RefreshPoints()
{
	global $db;
	$sql = "select points,back,dj from users where id = '{$_SESSION['usersid']}'";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$_SESSION['points'] = $rs['points'];
		$_SESSION['bankpoints'] = $rs['back'];
		$_SESSION['freeze'] = $rs['dj'];
	}
}

/*取得sql语句limit
 * $curPage:当前页
 * $PageSize:页大小
 */
function GetLimit($curPage,$PageSize=20)
{
	if($curPage < 1) $curPage = 1;
	$BeginNum = $PageSize * ($curPage - 1);
	return " limit " . $BeginNum . "," . $PageSize;
}

/*过滤字符串，防止sql注入
 * $str
 */
function FilterStr($str)
{
	return addslashes(trim($str));
}

function GetGameTableName($act,$t)
{
	$tablegame = "";
	$tablegame_auto = "";
	$tablegame_auto_tz = "";
	$tablegame_kg_users_tz = "";
	$tablegame_users_tz = "";
	$tableret = "";
	switch($act)
	{
		case "0"://gamefast28
			$tablegame = "gamefast28";
			$tablegame_auto = "gamefast28_auto";
			$tablegame_auto_tz = "gamefast28_auto_tz";
			$tablegame_kg_users_tz = "gamefast28_kg_users_tz";
			$tablegame_users_tz = "gamefast28_users_tz";
			break;
		case "1"://gamefast16
			$tablegame = "gamefast16";
			$tablegame_auto = "gamefast16_auto";
			$tablegame_auto_tz = "gamefast16_auto_tz";
			$tablegame_kg_users_tz = "gamefast16_kg_users_tz";
			$tablegame_users_tz = "gamefast16_users_tz";
			break;
		case "2"://gamefast11
			$tablegame = "gamefast11";
			$tablegame_auto = "gamefast11_auto";
			$tablegame_auto_tz = "gamefast11_auto_tz";
			$tablegame_kg_users_tz = "gamefast11_kg_users_tz";
			$tablegame_users_tz = "gamefast11_users_tz";
			break;
		case "3"://game28
			$tablegame = "game28";
			$tablegame_auto = "game28_auto";
			$tablegame_auto_tz = "game28_auto_tz";
			$tablegame_kg_users_tz = "game28_kg_users_tz";
			$tablegame_users_tz = "game28_users_tz";
			break;
 		case "4":
			$tablegame = "gameself28";
			$tablegame_auto = "gameself28_auto";
			$tablegame_auto_tz = "gameself28_auto_tz";
			$tablegame_kg_users_tz = "gameself28_kg_users_tz";
			$tablegame_users_tz = "gameself28_users_tz";
			break;
		case "5":
			$tablegame = "gamebj16";
			$tablegame_auto = "gamebj16_auto";
			$tablegame_auto_tz = "gamebj16_auto_tz";
			$tablegame_kg_users_tz = "gamebj16_kg_users_tz";
			$tablegame_users_tz = "gamebj16_users_tz";
			break;
		case "6":
			$tablegame = "gamepk10";
			$tablegame_auto = "gamepk10_auto";
			$tablegame_auto_tz = "gamepk10_auto_tz";
			$tablegame_kg_users_tz = "gamepk10_kg_users_tz";
			$tablegame_users_tz = "gamepk10_users_tz";
			break;
		case "7":
			$tablegame = "gamegj10";
			$tablegame_auto = "gamegj10_auto";
			$tablegame_auto_tz = "gamegj10_auto_tz";
			$tablegame_kg_users_tz = "gamegj10_kg_users_tz";
			$tablegame_users_tz = "gamegj10_users_tz";
			break;
		case "8":
			$tablegame = "gamecan28";
			$tablegame_auto = "gamecan28_auto";
			$tablegame_auto_tz = "gamecan28_auto_tz";
			$tablegame_kg_users_tz = "gamecan28_kg_users_tz";
			$tablegame_users_tz = "gamecan28_users_tz";
			break;
		case "9":
			$tablegame = "gamecan16";
			$tablegame_auto = "gamecan16_auto";
			$tablegame_auto_tz = "gamecan16_auto_tz";
			$tablegame_kg_users_tz = "gamecan16_kg_users_tz";
			$tablegame_users_tz = "gamecan16_users_tz";
			break;
		case "10":
			$tablegame = "gamecan11";
			$tablegame_auto = "gamecan11_auto";
			$tablegame_auto_tz = "gamecan11_auto_tz";
			$tablegame_kg_users_tz = "gamecan11_kg_users_tz";
			$tablegame_users_tz = "gamecan11_users_tz";
			break;
		default:
			break;
			
	}
	switch($t)
	{
		case "game":
			$tableret = $tablegame;
			break;
		case "auto":
			$tableret = $tablegame_auto;
			break;
		case "auto_tz":
			$tableret = $tablegame_auto_tz;
			break;
		case "kg_users_tz":
			$tableret = $tablegame_kg_users_tz;
			break;
		case "users_tz":
			$tableret = $tablegame_users_tz;
			break;
		default:
			break;
	}
	return $tableret;
}

function GetSubMenu($act,$sid)
{
    $subMenuID = $sid;
	$class = " class='pick' ";
	$RetDiv = "<div class='titles'>\r\n";
	$RetDiv .= "\t<ul class='list'>\r\n";
	$RetDiv .= "\t\t<li>\r\n";
	if($subMenuID == "") $subMenuID = 1;
	
	for($i = 1; $i <= 8; $i++)
	{
		switch($i)
		{
			case 1:
				$RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('sgame.php?act={$act}&sid={$i}')\"" . ">游戏首页</a>\r\n | \r\n";
			    break;
			
			case 2:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('sgamerule.php?act={$act}&sid={$i}')\"" . ">游戏规则</a>\r\n | \r\n";
			    break;
			case 3:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('sgamerecord.php?act={$act}&sid={$i}')\"" . ">投注记录</a>\r\n | \r\n";
			    break;
			case 4:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('smodel.php?act={$act}&sid={$i}')\"" . ">模式编辑</a>\r\n | \r\n";
			    break;
			case 5:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('sautopress.php?act={$act}&sid={$i}')\"" . ">自动投注</a>\r\n | \r\n";
			    break;
			case 7:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('strend.php?act={$act}&sid={$i}')\"" . ">走势图</a>\r\n | \r\n";
			    break;
			case 8:
			    $RetDiv .= "\t\t\t<a " . (($i == $subMenuID)?$class:"") . " href=\"javascript:getContent('swinstat.php?act={$act}&sid={$i}')\"" . ">盈利统计</a>\r\n";
			    break;
			default:
			    break;
		}
	}  
	$RetDiv .= "\t\t</li>\r\n";
	$RetDiv .= "\t</ul>";
	$RetDiv .= "</div>";
	return $RetDiv;
}

function GetHeadContent($act,$sid,&$aret)
{
	global $db;
	$tablegame = GetGameTableName($act,"game");
	$tablegametz = GetGameTableName($act,"users_tz");
	$SecondSub = -90;
	if($act == "0" || $act == "1" || $act == "2")
		$SecondSub = 10;
	//取当前待开奖
	$sql = "SELECT id,kgtime FROM {$tablegame} WHERE kj = 0 AND kgtime > DATE_ADD(NOW(),interval {$SecondSub} second) ORDER BY id LIMIT 1";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$preNo = $rs["id"];
		$prekgTime = DateDiff($rs["kgtime"],date("Y-m-d H:i:s"),"s");
		$aret['preno'] = $preNo;
		$aret['prekgtime'] = $prekgTime;
	}
	//取游戏配置
	$sql = "select game_kj_delay,game_tz_close from game_config where game_type='{$act}'";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$aret['game_kj_delay'] = $rs['game_kj_delay'];
    	$aret['game_tz_close'] = $rs['game_tz_close'];
	}
	
	//取最新一次开奖
	$sql = "SELECT id,kgjg,kgNo FROM {$tablegame} WHERE kj = 1 ORDER BY id DESC LIMIT 1";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$kgNo = $rs["id"];
		$kgResult = $rs["kgNo"];
		$arrkg = explode("|",$rs["kgjg"]);
	}
	//写头部
	$divPeriod = "<div class='period'>\r\n";
	$divPeriod .= "\t<div>\r\n";
	$divPeriod .= "\t\t<h3>第" . $kgNo . "期</h3>\r\n";
	$divPeriod .= "\t\t<span>开奖结果</span>\r\n";
	$divPeriod .= "\t</div>\r\n";
	$divPeriod .= "\t<ul>\r\n";
	if($act == "3" || $act == "4" || $act == "5")
	{
		$divPeriod .= "\t\t<li class='kaic'><a target='_blank' href='http://www.bwlc.net/bulletin/keno.html'>第三方开奖查询</a></li>\r\n";
	}
	else if($act == "6" || $act == "7")
	{
		$divPeriod .= "\t\t<li class='kaic'><a target='_blank' href='http://www.bwlc.net/bulletin/trax.html'>第三方开奖查询</a></li>\r\n";
	}
	$divPeriod .= "\t\t<li>" . str_replace("|",",",$kgResult) . "</li>\r\n";
	$divPeriod .= "\t\t<li class='pers'>\r\n";
	$divPeriod .= "\t\t\t一区号码:" . "<i>{$arrkg[0]}</i>\r\n"; 
	$divPeriod .= "\t\t\t二区号码:" . "<i>{$arrkg[1]}</i>\r\n";
	if($act == "2" || $act == "6" || $act == "10") 
	{
		$divPeriod .= "\t\t\t结果:" . "<em>{$arrkg[2]}</em>\r\n";
	}
	else
	{
		$divPeriod .= "\t\t\t三区号码:" . "<i>{$arrkg[2]}</i>\r\n";
		$divPeriod .= "\t\t\t结果:" . "<em>{$arrkg[3]}</em>\r\n";
	}
	$divPeriod .= "\t\t</li>\r\n";
	$divPeriod .= "\t</ul>\r\n";
	$divPeriod .= "</div>\r\n";
	
	//写中间
	$sql = "SELECT 	COUNT(id) totalcount,IFNULL(SUM(hdpoints - points),0) winpoints,COUNT(IF(hdpoints - points > 0,TRUE,NULL)) AS wincount,
					COUNT(IF(hdpoints - points < 0,TRUE,NULL)) AS losscount
	        FROM {$tablegametz} WHERE uid = {$_SESSION['usersid']} AND `time` > CURDATE()";
	$result = $db->query($sql);
	if($rs = $db->fetch_array($result))
	{
		$totalCount = $rs["totalcount"];
		$sumWinPoint = $rs["winpoints"];
		$winCount = $rs["wincount"];
		$lossCount = $rs["losscount"];
		$winOdds = round($winCount/($winCount+$lossCount) * 100);
	}
	$divTies = "<div class='ties'>\r\n";
	$divTies .= "\t<ul>\r\n";      
	$divTies .= "\t\t<li id='liTimer'><i></i><em></em></li>\r\n";
	$divTies .= "\t\t<li>今日盈亏:<em>".Trans($sumWinPoint)."</em> 参与:<i>{$totalCount}</i>期 胜率:<i>{$winOdds}%</i>\r\n";
	$divTies .= "\t</ul>\r\n";
	$divTies .= "\t<p><a href=\"javascript:getContent('sautopress.php?act={$act}&sid=5');\">自动投注>></a></p>\r\n";
	$divTies .= "</div>\r\n";
	
	return $divPeriod . $divTies; 
}
 
function GetRewardJS($act,$arrR,$viewtype)
{
	$kjSec = $arrR['prekgtime'] + $arrR['game_kj_delay'];
	$StopSec = $arrR['prekgtime'] - $arrR['game_tz_close'];
	$No = $arrR['preno'];
    $jsFun = "";
    $RefreshSecond = -10;
    $ReSecond = 12;
    if($act == "0" || $act == "1" || $act == "2")
    {
		$RefreshSecond = -5;
    	$ReSecond = 5;	
    }
    if($viewtype == "game") //在开奖列表里时
    {
		$jsFun = "
		function refreshContent()
		{
			if(kjSec <= 0)
			{
				if(kjSec == {$RefreshSecond})
				{
					$('#liTimer').html('Loading......');
					getContent('sgame.php?act={$act}&t=' + Math.random());
				}
				else if(kjSec < {$RefreshSecond} && Math.abs(kjSec) % {$ReSecond} == 0){
					$('#liTimer').html('Loading......');
					getContent('sgame.php?act={$act}&t=' + Math.random());
				} else {
					$('#liTimer').html('第<i>' + curNo + '</i>期 正在开奖，请稍后!');
				}
				kjSec--;
			}
			else
			{
				if(stopSec == 0){
					$('#scur_{$No}').html('');
					$('#scur_{$No}').attr('class','open3');
				}
				if(stopSec > 0){
				 	$('#liTimer').html('第<i>' +curNo+'</i>期 还有<em>' + stopSec + '</em>秒停止下注!');
				} else {
				 	$('#liTimer').html('第<i>'+curNo+'</i>期 停止下注，还有<em> ' + kjSec + ' </em>秒开奖!');
				}
				kjSec--;
				stopSec--;
			}
		}
		";
    }
    else
    {
		$jsFun = "
		function refreshContent()
			{
				if(kjSec <= 0)
				{
					if(kjSec <= -10){
						$('#liTimer').html('第<i>' + curNo + '</i>期 已开奖，请刷新!');
					} else {
					 	$('#liTimer').html('第<i>' + curNo + '</i>期 正在开奖，请稍后!');
					}
					kjSec--;
				}
				else
				{
				 	if(stopSec > 0){
				 	 	$('#liTimer').html('第<i>' +curNo+'</i>期 还有<em>' + stopSec + '</em>秒停止下注!');
				 	} else {
				 	 	$('#liTimer').html('第<i>'+curNo+'</i>期 停止下注，还有<em> ' + kjSec + ' </em>秒开奖!');
				 	}
				 	kjSec--;
				 	stopSec--;
				}
			}
		";
    }
    $js = "<script type=\"text/javascript\">";
	$js .= "
		var curNo = '{$No}';
		var stopSec = '{$StopSec}';
		var kjSec = '{$kjSec}';
		clearInterval(timerid);
		timerid = setInterval('refreshContent()',1000);
		$('#iPoints').html('". Trans($_SESSION['points']) ."');
		$('#iBankPoints').html('". Trans($_SESSION['bankpoints']) ."');
		";
	$js .= $jsFun;
	$js .= "</script>\r\n";
	return $js;
}

function ChangeEncodeU2G($s)
{
    return iconv("UTF-8", "GB2312//IGNORE", $s);
}

function ChangeEncodeG2U($s)
{
    return iconv("GB2312", "UTF-8", $s);
}

function ArrayChangeEncode(& $arrfrom)
{
	foreach($arrfrom as $k => & $arr)
    {
		foreach($arr as $t => & $v)
		{
			$v = ChangeEncodeG2U($v);
		}
    }      
}

function Trans($num)
{
    return number_format($num);
}

function PostSMS($mobile,$content)
{
	$target = "http://sms.106jiekou.com/utf8/sms.aspx";
	//替换成自己的测试账号,参数顺序和wenservice对应
	$post_data = "account=aa522117&password=522117&mobile={$mobile}&content=".rawurlencode($content);
	
	$smsResult = Post($post_data, $target);
	//$xml = simplexml_load_string($smsResult);
	//$result = (string) $xml->result;
	$ret = "ok";
	switch($smsResult)
	{
		case "100":
			$ret = "ok";
			break;
		case "101":
			$ret = "验证失败";
			break;
		case "102":
			$ret = "手机号码格式不正确";
			break;
		case "103":
			$ret = "会员级别不够";
			break;
		case "104":
			$ret = "内容未审核";
			break;
		case "105":
			$ret = "内容过多";
			break;
		case "106":
			$ret = "账户余额不足";
			break;
		case "107":
			$ret = "Ip受限";
			break;
		case "108":
			$ret = "手机号码发送太频繁，请换号或隔天再发";
			break;
		case "109":
			$ret = "帐号被锁定";
			break;
		case "110":
			$ret = "发送通道不正确";
			break;
		case "111":
			$ret = "当前时间段禁止短信发送";
			break;
		case "120":
			$ret = "系统升级";
			break;
		default:
			$ret = "未知错误:" . $smsResult;
			break;
	}
	return $ret;
}

function Post($curlPost,$url){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_NOBODY, true);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
	$return_str = curl_exec($curl);
	curl_close($curl);
	return $return_str;
}


function WriteLog($Msg,$flag=FILE_APPEND)
{
    $LogFile = dirname(dirname(__FILE__)) . '/log/logtext.txt';    
    $Msg = date("Y-m-d H:i:m ") . $Msg ."\r\n";
    file_put_contents($LogFile, $Msg,$flag);
}
function LogFormat($Msg)
{
	return date("Y-m-d H:i:m ") . $Msg ."\r\n"; 
}

function business_check(){
	global $db,$web_dbtop,$web_dir;
	$query=$db->query("Select id From {$web_dbtop}business where uid=" .intval($_COOKIE["usersid"]));
		if(!$rs=$db->fetch_array($query)){
			echo "<script>alert('对不起，您没有该权限！');location.href='".$web_dir."index.php';</script>";
	  		exit;
		}
}

function usersip() {
if (getenv('HTTP_CLIENT_IP')) {
		$ip = getenv('HTTP_CLIENT_IP');
	}elseif (getenv('HTTP_X_FORWARDED_FOR')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}elseif (getenv('HTTP_X_FORWARDED')) {
		$ip = getenv('HTTP_X_FORWARDED');
	}elseif (getenv('HTTP_FORWARDED_FOR')) {
		$ip = getenv('HTTP_FORWARDED_FOR');
	}elseif (getenv('HTTP_FORWARDED')) {
		$ip = getenv('HTTP_FORWARDED');
	}else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

function cnsubstr($str_cut,$length)
{ 
    if (strlen($str_cut) > $length)
    { 
        for($i=0; $i < $length; $i++) 
        if (ord($str_cut[$i]) > 128)    $i++; 
        $str_cut = substr($str_cut,0,$i); 
    } 
    return $str_cut; 
}


function random($length) { 
$hash = ''; 
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; 

$max = strlen($chars) - 1; 

for($i = 0; $i < $length; $i++) { 
$hash .= $chars[mt_rand(0, $max)]; 
} 
return $hash; 

}

function showid($tables,$tablesname,$id){
	global $db,$web_dbtop;
	$query=$db->query("Select $tablesname from $web_dbtop$tables where email='".$id."'");
	if($rs=$db->fetch_array($query)){
		return $rs[$tablesname];
	}
}

function msg_num($type){
	global $db,$web_dbtop;
	$sql="select count(id) from {$web_dbtop}msg";
	if($type==1){
		$sql.=" where usersid=".intval($_COOKIE["usersid"])." and del=0 and look=0";
	}else{
		$sql.=" where mid=".intval($_COOKIE["usersid"])." and del=0 and look=0";
	}
	return $db->result_first($sql);
}

function ck_secans($secans){
global $db,$web_dbtop;
	$query=$db->query("Select secans From {$web_dbtop}users where id=" .intval($_COOKIE["usersid"]). " And password='" .str_check($_COOKIE["password"]). "'");
	if($rs=$db->fetch_array($query)){
		if($rs["secans"]!=$secans){
			echo "<script language=javascript>alert('对不起，您输入的安全答案错误，请核对和后再试！');history.go(-1);</script>";
			exit;
		}
	}
}

function backlog($mun,$type){
	global $db,$web_dbtop;
	if($type==1){
		$db->query("INSERT INTO {$web_dbtop}backlog (time,log,points,back,usersid) VALUES ('".date("Y-m-d H:i:s")."','存',".-$mun.",".$mun.",".intval($_COOKIE["usersid"]).")");
	}else{
		$db->query("INSERT INTO {$web_dbtop}backlog (time,log,points,back,usersid) VALUES ('".date("Y-m-d H:i:s")."','取',".$mun.",".-$mun.",".intval($_COOKIE["usersid"]).")");
	}
}

function userslog($logtype,$log,$points,$experience,$usersid=''){
	global $db,$web_dbtop;
	if(!$usersid)
		$usersid=intval($_COOKIE["usersid"]);
	$db->query("INSERT INTO {$web_dbtop}userslog (time,logtype,log,points,experience,usersid) VALUES ('".date("Y-m-d H:i:s")."',".intval($logtype).",'".str_check($log)."',".intval($points).",".intval($experience).",".$usersid.")");
}

function showstars($num) {
	global $web_dir;
	$starthreshold=3;
	$alt = 'alt="等级: '.$num.'级"';
	$ret = "";
	if(empty($starthreshold)) {
		for($i = 0; $i < $num; $i++) {
			$ret .= '<img src="'.$web_dir.'img/score/1.gif" '.$alt.' />';
		}
	} else {
		for($i = 6; $i > 0; $i--) {
			$numlevel = intval($num / pow($starthreshold, ($i - 1)));
			$num = ($num % pow($starthreshold, ($i - 1)));
			for($j = 0; $j < $numlevel; $j++) {
				$ret .= '<img src="'.$web_dir.'img/score/'.$i.'.gif" '.$alt.' />';
			}
		}
	}
	return $ret;
}

function userslive($experience){
	global $db,$web_dbtop;
	$query=$db->query("Select stars from {$web_dbtop}usergroups where $experience BETWEEN creditslower AND creditshigher Order by id desc");
	if($rs=$db->fetch_array($query)){
		return $rs["stars"];
	}
}

function showselect($id){
	global $db,$web_dbtop;
	echo "<OPTION value=\"\" ".(!$id?"selected":"").">全部礼品</OPTION>";
	$query=$db->query("Select * from {$web_dbtop}ctype where typeid=0 Order by sort asc,id desc");
	while($rs=$db->fetch_array($query)){
		echo "<OPTION value=".$rs["id"]." ".($id==$rs["id"]?"selected":"").">".$rs["name"]."</OPTION>";
		$query_f=$db->query("Select * from {$web_dbtop}ctype where typeid=".$rs["id"]." Order by sort asc,id desc");
		while($rs_f=$db->fetch_array($query_f)){
			echo "<OPTION value=".$rs_f["id"]." ".($id==$rs_f["id"]?"selected":"").">├--".$rs_f["name"]."</OPTION>";
		}
	}
}

function showcontent($tables,$tablesname,$id){
	global $db,$web_dbtop;
	$query=$db->query("Select $tablesname from $web_dbtop$tables where id=$id");
	if($rs=$db->fetch_array($query)){
		return $rs[$tablesname];
	}
}

function typesid($id){
	global $db,$web_dbtop;
	$query=$db->query("Select * from {$web_dbtop}ctype where typeid=$id Order by sort asc,id desc");
	while($rs=$db->fetch_array($query)){
		$content.=$rs["id"].",";
	}
	return rtrim($content,",");
}

function delkey($content){
	global $web_commentskey;
	$commentskey=explode("|",$web_commentskey);
	for($i=0; $i<count($commentskey); $i++){
		$content=str_replace($commentskey[$i],"*",$content);
	}
	return htmlspecialchars($content);
}

function checkEmail($inAddress){ 
 	return (ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",$inAddress)); 
}

function cardtypeselect(){
	global $db,$web_dbtop;
	echo"<select name=\"cardtype\">";
   	echo"<option value=\"\">请选择充值卡类型</option>";
	$query=$db->query("Select * FROM {$web_dbtop}cardtype Order by id desc");
	while($rs=$db->fetch_array($query)){
		echo"<option value=".$rs["id"].">".$rs["cardname"]."</option>";
	}
    echo "</select>";
}

function showbusinessid($uid){
	global $db,$web_dbtop;
	$query=$db->query("Select id from {$web_dbtop}business where uid=$uid");
	if($rs=$db->fetch_array($query)){
		return $rs["id"];
	}
}

function showcardtype($id){
	global $db,$web_dbtop;
	$query=$db->query("Select cardname from {$web_dbtop}cardtype where id=$id");
	if($rs=$db->fetch_array($query)){
		return $rs["cardname"];
	}
}

function createrandstring($length,$type) { 
	$hash = ''; 
	$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	switch($type){
	case 0:
		$max=9;
		break;
	case 1:
		$max=35;
		break;
	case 2:
		$max = strlen($chars) - 1; 
		break;
	default:
		$max=9;
		break;
	}
	for($i = 0; $i < $length; $i++){ 
		$hash .= $chars[mt_rand(0, $max)]; 
	} 
	return $hash; 
}

function DateDiff($date1, $date2, $unit = ""){
switch ($unit) { 
case 's': 
$dividend = 1; 
break; 
case 'i': 
$dividend = 60; 
break; 
case 'h': 
$dividend = 3600; 
break; 
case 'd': 
$dividend = 86400; 
break; 
default: 
$dividend = 86400; 
} 
$time1 = strtotime($date1);
$time2 = strtotime($date2);
if ($time1 && $time2)
return (float)($time1 - $time2) / $dividend;
return false;
}

function zint($val){
	if($val>0){
		return $val;
	}else{
		return 0;
	}
}

function game11pl($num){
	$game11_array = array(36,18,12,9,7.2,6,7.2,9,12,18,36);
	return $game11_array[$num-2];
	unset($game11_array);
}

function game16pl($num){
	$game16_array = array(216,72,36,21.6,14.4,10.29,8.64,8,8,8.64,10.29,14.4,21.6,36,72,216);
	return $game16_array[$num-3];
	unset($game16_array);
}

function game28pl($num){
	$game28_array = array(1000,333.33,166.67,100,66.66,47.61,35.71,27.77,22.22,18.18,15.87,14.49,13.69,13.33,13.33,13.69,14.49,15.87,18.18,22.22,27.77,35.71,47.61,66.66,100,166.66,333.33,1000);
	return $game28_array[$num];
	unset($game28_array);
}

function fsockurl($httpurl){
	$url=explode("/",$httpurl);
	$urls=$url[2];
	if(stristr($urls,":")){
	$w_url=explode(":",$urls);
	$urls=$w_url[0];
	$port=$w_url[1];
	}else{
	$port=80;
	}
	for($i=3;$i<count($url);$i++){ 
		$pstr .= "/".$url[$i]; 
	}
	$fp = @fsockopen($urls,$port);
	if($fp){
		$out = "GET $pstr HTTP/1.1\r\n"; 
		$out .= "Host: $urls\r\n"; 
		$out .= "Connection: Close\r\n\r\n"; 
		fwrite($fp, $out); 
		while (!feof($fp)){ 
			$httpcontent.=fgets($fp, 1024);
		} 
		fclose($fp);
	}
	$httpcontent=explode("\r\n\r\n",$httpcontent,2); 
	return $httpcontent[1];
}

function GetBodyc($string,$start,$end){
	$start=stripcslashes($start);
	$end=stripcslashes($end);
	$message = @explode($start,$string);
	if(count($message) < 1) return "";
	$message = @explode($end,$message[1]);
	if(count($message)>1){
		return $message[0];
	} else{
		return "";
	}
}

function pro_rand($pro, &$res, $num=1){
	$pro_sum = array_sum($pro);
	for($i = 0; $i < $num; $i++){
		$rand_num = mt_rand(1, $pro_sum);
		reset($pro);
		foreach($pro as $key => $value){
				if($rand_num <= $value){
					break;
				}else{
					$rand_num -= $value;
				}
		}
		$res[$i] = $key;
	}
}

function dodgejg($pk,$ww){
	 if($pk - $ww == -1 || $pk - $ww == 2){    
        return 1;      
     }elseif($pk - $ww == 1 || $pk - $ww == -2){    
        return 2;     
     }else{    
     	return 3;      
     }
}

function today_posts_num($id){
	global $db,$web_dbtop;
	$sql="select count(id) from {$web_dbtop}bbs_posts where STR_TO_DATE(time,'%Y-%m-%d')='".date("Y-m-d")."'";
	$sql.=" and section=".intval($id);
	return $db->result_first($sql);
}

function posts_num($id){
	global $db,$web_dbtop;
	$sql="select count(id) from {$web_dbtop}bbs_posts where";
	$sql.=" section=".intval($id);
	return $db->result_first($sql);
}

function reply_num($id){
	global $db,$web_dbtop;
	$sql="select count({$web_dbtop}bbs_reply.id) from {$web_dbtop}bbs_reply,{$web_dbtop}bbs_posts where";
	$sql.=" {$web_dbtop}bbs_reply.pid={$web_dbtop}bbs_posts.id and {$web_dbtop}bbs_posts.section=".intval($id);
	return $db->result_first($sql);
}

function f_reply_num($id){
	global $db,$web_dbtop;
	$sql="select count(id) from {$web_dbtop}bbs_reply where";
	$sql.=" pid=".intval($id);
	return $db->result_first($sql);
}

function f_final_id($id){
	global $db,$web_dbtop;
	$query=$db->query("Select uid from {$web_dbtop}bbs_reply where pid=".intval($id)." Order by id desc");
	if($rs=$db->fetch_array($query)){
		return showcontent("users","name",$rs["uid"]);
	}
	return "&nbsp;";
}

function flashslide($Slidewidth,$Slideheight){
	global $db,$web_dbtop,$web_dir,$web_slidedir;
	$flashslide="<script type=text/javascript>\n";
	$flashslide.="var swf_width=".$Slidewidth.";\n";
	$flashslide.="var swf_height=".$Slideheight.";\n";
	$query=$db->query("select slidepic,slideurl from {$web_dbtop}slide Order by sort asc,id desc");
	while($rs=$db->fetch_array($query)){
		$i++;
		if(stristr($rs["slidepic"],"http://")){
		$images=$rs["slidepic"];
		}else{
		$images=$web_dir.$web_slidedir.$rs["slidepic"];
		}
	$pic.=$images."|";
	$links.=$rs["slideurl"]."|";
	}
	$flashslide.="var files='".rtrim($pic,"|")."';\n";
	$flashslide.="var links='".rtrim($links,"|")."';\n";
	$flashslide.="var texts='';\n";
	$flashslide.="document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\">');\n";
	$flashslide.="document.write('<param name=\"movie\" value=\"".$web_dir."inc/flash.swf\"><param name=\"quality\" value=\"high\">');\n";
	$flashslide.="document.write('<param name=\"menu\" value=\"false\"><param name=\"wmode\" value=\"opaque\">');\n";
	$flashslide.="document.write('<param name=\"FlashVars\" value=\"bcastr_file='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'\">');\n";
	$flashslide.="document.write('<embed src=\"".$web_dir."inc/flash.swf\" wmode=\"opaque\" FlashVars=\"bcastr_file='+files+'&bcastr_link='+links+'&bcastr_title='+texts+'& menu=\"false\" quality=\"high\" width=\"'+ swf_width +'\" height=\"'+ swf_height +'\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />'); document.write('</object>');\n";
	$flashslide.="</script>";
	return $flashslide;
}
?>
